<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/8
 * Time: 15:42
 */

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MobileMark extends Model
{
    protected $table = 'ivy_mobile_mark';
    public $timestamps = false;
    protected $primaryKey = 'id';

    /*
     * 存储地理位置信息
     * */
    public static function saveMark($request)
    {
        $params = $request->all();

        $location_push_flag_key = 'location_push_flag:'.md5($params['mobile_unique_code'].$params['province'].$params['city'].$params['address']);
        if(!empty(Redis::get($location_push_flag_key)))
            return json_decode(Redis::get($location_push_flag_key), true);

        $model = MobileMark::where(['mobile_unique_code'=> $params['mobile_unique_code']])->first();
        if(empty($model))
            $model = new MobileMark();
        foreach ($params as $key => $value){
            if (!in_array($key, ['mobile_unique_code', 'province', 'city', 'district',
                'address', 'post_code']) || empty($value))
                continue;
            $model->$key = $value;
        }
        $model->option_time = time();
        if(!$model->save())
            return false;

        Redis::setex($location_push_flag_key, 3600, json_encode($model->toArray()));
        return $model->toArray();
    }

    /*
     * 获取设备信息
     * */
    public static function getRowsArray($where)
    {
        $key = 'mobileMark_rows:'.md5(json_encode($where));
        if(!empty(Redis::get($key)))
            return json_decode(Redis::get($key), true);

        $rows = self::where($where)->first();
        if(!empty($rows)){
            $rows = $rows->toArray();
            Redis::setex($key, 3600, json_encode($rows));
        }
        return $rows;
    }
}